import React from 'react';
import type { Dispatch, SetStateAction } from 'react';
import styles from './index.less';
import { Checkbox, Tooltip } from 'antd';
import { useTablePipeline, features } from 'ali-react-table';
import { TjTable } from '@/pages/ETrade/components';
import moment from 'moment';

import { TRAlert, PLoading } from '#/components/index.js';
import { PlusSquareOutlined, MinusSquareOutlined, FileSearchOutlined } from '#/utils/antdIcons.js';
import { downloadHandle } from '#/utils/utils.js';

import { postQuantityPriceExport } from '../../service';
import {
  tradeDirectionOptions,
  positionsCalculateOptions,
  contractSourceOptions,
  operationList,
  totalMap,
} from '../../dictionary';
import type { IOptionType, IListType } from '../../type';
import { IOperationType, IContractSourceType, IContractType } from '../../type';
import { havePermissions, ToFixed } from '../../tool';

interface IProps {
  /**
   * 是否显示量价图
   */
  visible?: boolean;
  /**
   * 展开的行对应的合约Id
   */
  contractId?: string;
  /**
   * 数据源
   */
  dataSource?: IListType[];
  /**
   * 选择参数
   */
  selectedRowKeys?: string[];
  /**
   * 改变选择参数
   */
  setSelectedRowKeys?: Dispatch<SetStateAction<string[]>>;
  /**
   * 操作权限列表
   */
  buttonPermissions?: any;
  /**
   * 点击合约分析图
   */
  showContratCharts?: (record: any) => void;
  /**
   * 编辑数据
   */
  onEdit?: (record: IListType) => void;
  /**
   * 删除数据
   */
  onDetele?: (record: IListType) => void;
  /**
   * 展示详情
   */
  onDetail?: (record: IListType) => void;
  /**
   * 合计数据
   */
  overviewData: any;
}

const List = (props: IProps) => {
  const {
    visible = false,
    contractId,
    dataSource = [],
    selectedRowKeys = [],
    buttonPermissions,
    overviewData,
    setSelectedRowKeys,
    showContratCharts,
    onEdit,
    onDetail,
    onDetele,
  } = props;

  // 详情
  const _onDetail = (record: any) => {
    onDetail && onDetail(record);
  };

  // 编辑
  const _onEdit = (record: any) => {
    onEdit && onEdit(record);
  };

  // 删除
  const _onDetele = (record: any) => {
    onDetele && onDetele(record);
  };

  // 操作
  const onOperation = async (item: IOptionType, record: any) => {
    if (item.value === IOperationType.DETAIL) {
      _onDetail(record);
    } else if (
      item.value === IOperationType.EDIT &&
      record?.contractSource === IContractSourceType.USER_UPLOAD
    ) {
      const resoult = havePermissions('pendingRemoveButtonV2', buttonPermissions);
      if (resoult) {
        _onEdit(record);
      }
    } else if (
      item.value === IOperationType.DETELE &&
      record?.contractSource === IContractSourceType.USER_UPLOAD
    ) {
      const resoult = havePermissions('pendingRemoveButtonV2', buttonPermissions);
      if (resoult) {
        _onDetele(record);
      }
    } else if (item.value === IOperationType.EXPORT) {
      const result = havePermissions('ContractManagementQuantityPriceExport', buttonPermissions);
      if (!result) return;
      const params = {
        contractId: record.contractId,
        contractSource: record.contractSource,
        stationId: record.stationId,
      };
      PLoading.show('正在导出...');
      const data = await postQuantityPriceExport(params);
      if (data.data && data.data instanceof Blob) {
        PLoading.dismiss();
        const realFileName = data.response.headers.get('content-disposition').split('filename=')[1];
        downloadHandle(data.data, decodeURI(realFileName));
      } else {
        PLoading.dismiss();
        TRAlert.error(data?.message || '请求失败');
      }
      PLoading.dismiss();
    }
  };

  const width = 280 + (visible ? 0 : 358);

  const columns = [
    {
      code: 'stationName',
      name: '交易单元',
      width: 130,
      render(v: string) {
        return v || '-';
      },
    },
    {
      code: 'tradeRole',
      name: '方向',
      width: 60,
      render(v: string) {
        const data = v ? tradeDirectionOptions.find((item) => item.value === v) : {};
        return data?.label || '-';
      },
    },
    {
      code: 'contractName',
      name: '合约名称',
      width,
      render(v: string, record: IListType) {
        return (
          <div className={styles.title}>
            <Tooltip placement="topLeft" title={v}>
              <div className={styles.text}>{v || '-'}</div>
            </Tooltip>
            {v ? (
              <div
                className={styles.titleLogo}
                onClick={() => showContratCharts && showContratCharts(record)}
              >
                <FileSearchOutlined className={styles.logo} />
              </div>
            ) : null}
          </div>
        );
      },
    },
    {
      code: 'contractType',
      name: '合约类型',
      width: 100,
      render(v: string) {
        return v ?? '-';
      },
    },
    {
      code: 'content',
      name: '关联情况',
      width: 100,
      render(v: string, record: IListType) {
        const type =
          record?.childrenContractList &&
          record?.childrenContractList?.length > 0 &&
          record.type === IContractType.MAINCONTRACT
            ? '主合约'
            : record.type === IContractType.SUBCONTRACT
            ? '转让合约'
            : '-';
        return type;
      },
    },
    {
      code: 'contractStartDate',
      name: '执行期',
      width: 160,
      render(v: string, record: any) {
        const data =
          record.contractStartDate && record.contractEndDate
            ? `${moment(record.contractStartDate).format('YYYYMMDD')}-${moment(
                record.contractEndDate,
              ).format('YYYYMMDD')}`
            : '-';
        return data;
      },
    },
    {
      code: 'totalContractQuantity',
      name: '合约电量(MWh)',
      width: 120,
      render(v: string) {
        const text = ToFixed(v, 3);
        return text ?? '-';
      },
    },
    {
      code: 'statisticsPower',
      name: '统计电量(MWh)',
      width: 120,
      render(v: string) {
        const text = ToFixed(v, 3);
        return text ?? '-';
      },
    },
    {
      code: 'totalContractPrice',
      name: '均价(元/MWh)',
      width: 120,
      render(v: string) {
        const text = ToFixed(v, 2);
        return text ?? '-';
      },
    },
    {
      code: 'storageCapacityCalc',
      name: '仓位计算',
      width: 100,
      render(v: string) {
        const data = v ? positionsCalculateOptions.find((item) => item.value === v) : {};
        return data?.label || '-';
      },
    },
    {
      code: 'contractSource',
      name: '来源',
      width: 140,
      render(v: string) {
        const data = v ? contractSourceOptions.find((item) => item.value === v) : {};
        return data?.label || '-';
      },
    },
    {
      code: 'operation',
      name: '操作',
      width: 164,
      lock: true,
      render(v: number, record: any) {
        if (record.contractName === '合计') return;
        return (
          <div className={styles.options}>
            {operationList.map((item) => {
              return (
                <div
                  key={item.value}
                  className={`${
                    (item.value === IOperationType.EDIT || item.value === IOperationType.DETELE) &&
                    (record?.contractSource === IContractSourceType.TRADING_CENTER ||
                      record?.contractSource === IContractSourceType.TRADING_CENTER_NOMAL ||
                      record?.contractSource === IContractSourceType.TRADING_CENTER_VIRTUAL)
                      ? styles.disableItem
                      : styles.item
                  }`}
                  onClick={() => onOperation(item, record)}
                >
                  {item.label}
                </div>
              );
            })}
          </div>
        );
      },
    },
  ];

  const pipeline = useTablePipeline({
    components: { Checkbox, PlusSquareOutlined, MinusSquareOutlined },
  })
    .input({ dataSource: dataSource, columns: columns as any })
    .primaryKey('contractAndstationId')
    .use(
      features.treeMode({
        clickArea: 'cell',
      }),
    )
    .use(
      features.multiSelect({
        value: selectedRowKeys,
        highlightRowWhenSelected: true,
        checkboxPlacement: 'start',
        checkboxColumn: { lock: true },
        clickArea: 'cell',
        onChange: (nextValue: string[]) => {
          setSelectedRowKeys && setSelectedRowKeys(nextValue);
        },
      }),
    )
    .appendRowPropsGetter((_row): any => {
      const color = '#222629';
      const otherColor = '#21323E';
      return {
        style: {
          '--bgcolor': visible && contractId === _row?.contractId ? otherColor : color,
          '--hover-bgcolor': visible && contractId === _row?.contractId ? otherColor : color,
          '--highlight-bgcolor': visible && contractId === _row?.contractId ? otherColor : color,
        },
      };
    });

  return (
    <>
      <div className={styles.total}>
        {totalMap.map((i: any, index: number) => (
          <div style={{ marginRight: 64 }} key={index}>
            <div className={styles.data}>
              <div>
                {i.name}：
                <span>{ToFixed(overviewData?.[i.key], i.name.includes('电量') ? 3 : 2)}</span>
                {i.unit}
              </div>
            </div>
          </div>
        ))}
      </div>
      <div className={`${styles.container}`}>
        <TjTable useVirtual="auto" defaultColumnWidth={90} {...pipeline.getProps()} />
      </div>
    </>
  );
};

export default List;
